package cn.johnyu;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.*;

public class MyContainer<T> {
    private T[] data;
    private int size=0;
    public MyContainer(){
        data=(T[])new Object[1000];
    }
    public void add(int len, Supplier<T> supplier){
        for (int i = 0; i < len; i++) {
            data[i]=supplier.get();
        }
        size=len;
    }
    public Optional<T> get(int index){
        return Optional.ofNullable(data[index]);
    }

    public List<T> map(Function<T,T> function){
        List<T> list=new ArrayList<>();
        for (int i = 0; i < size; i++) {
            list.add(function.apply(data[i]));
        }
        return list;
    }

    public List<Double> mapToDouble(Function<T,Double> function){
        List<Double> list=new ArrayList<>();
        for (int i = 0; i < size; i++) {
            list.add(function.apply(data[i]));
        }
        return list;
    }

    public void sort(BiFunction<T,T,Integer> biFunction){
        T t=null;
        for (int i = 0; i <size-1 ; i++) {
            for(int j=i+1;j<size;j++){
                if(biFunction.apply(data[i],data[j])>0){
                    t=data[i];
                    data[i]=data[j];
                    data[j]=t;
                }
            }

        }
    }



    public void forEach(Consumer<T> consumer){
        for (int i = 0; i < size; i++) {
            consumer.accept(data[i]);
        }
    }

    public List<T> filter(Predicate<T> predicate){
        List<T> list=new ArrayList<>();
        for (int i = 0; i < size; i++) {
            if(predicate.test(data[i])){
                list.add(data[i]);
            }
        }
        return list;
    }



    public static void main(String[] args) {
        MyContainer<String> mc = new MyContainer<>();
        mc.add(100,()->Math.random()+"");
        mc.sort((t1,t2)->t1.compareTo(t2));

        mc.forEach(s-> System.out.println(s));

//        mc.map((s1)->"$: "+s1)
//        .stream()
//        .forEach(System.out::println);

//       List<Double> dd= mc.mapToDouble((s)->Double.parseDouble(s));
//       dd.stream().forEach(d-> System.out.println(d+9));


//        List<String> list=mc.filter(s->s.startsWith("0.5"));
//        list.stream().forEach(s-> System.out.println(s));
       // mc.forEach(s-> System.out.println(s));
//        String s=mc.get(3).orElse("0.99897979898");
//        System.out.println(s);
    }


}
